import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Button } from 'antd';
import PateoModalForm from '../../../components/common/PateoModalForm';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import { PlusOutlined } from '@ant-design/icons';
import { getDicByKey, findDicByCode, comboHolder, comboSelectHolder, filterAuth } from '@/support/common';

const mapStateToProps = (state: any) => ({
  userComment: state.userComment,
  loading: state.loading.effects['userComment/getFetchPage']
});
class CommentType extends PureComponent<any, any> {

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      visible: false,
      postUrl: '',
      formData: {}
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "userComment/getFetchPage",
      payload: { url: "/userfeedback/commenttypefindbypage" }
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userComment/initData'
    });
  }

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'userComment/getFetchPage',
      payload: { url: '/userfeedback/commenttypefindbypage', ...formValues },
    });
  };

  handleAdd = () => {
    this.setState({
      visible: true,
      postUrl: '/userfeedback/addcommenttype',
    });
  };

  handleEdit = (record: any) => {
    this.setState({
      formData: record,
      visible: true,
      postUrl: '/userfeedback/editcommenttype/' + record.sid,
    });
  };

  handleStatus = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userComment/getDataWithRes',
      payload: { url: '/userfeedback/editcommenttypestatus', sid: record.sid, status: record.status === '1' ? 0 : 1 },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          message.success('操作成功！');
          this.handleFlushPage();
        }
      },
    });
  };

  render() {
    const { userComment: { pageData: { list, pagination } }, loading,
      pathname, projectOptions, permissions, dicData } = this.props;
    const { formValues, visible, postUrl, formData } = this.state;
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        }
      }, {
        title: '编码',
        dataIndex: 'sid'
      }, {
        title: '所属项目',
        dataIndex: 'projectId',
        render: (text: any) => {
          if (text) {
            let curOptions = projectOptions.filter((item: any) => item.value === text);
            if (curOptions && curOptions.length > 0) {
              return curOptions[0].label;
            } else {
              return text;
            }
          } else {
            return text;
          }
        }
      }, {
        title: '类型名称',
        dataIndex: 'typeName'
      }, {
        title: '系统终端',
        dataIndex: 'typeSources',
        render: (text: any) => {
          return text ? getDicByKey(dicData, 'commentTypeSources', text) : text;
        }
      }, {
        title: '状态',
        dataIndex: 'status',
        render: (text: any) => text === '1' ? '启用' : '禁用',
      }, {
        title: '操作',
        dataIndex: '操作',
        width: 100,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'userComment_doEditType',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: record.status === '1' ? '禁用' : '启用',
              key: 'status',
              auth: 'userComment_doEditTypeStatus',
              Popconfirm: true,
              message: '是否确认' + (record.status === '1' ? '禁用' : '启用') + '？',
              onConfirm: () => this.handleStatus(record),
            }
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      }
    ];
    const formItems = [
      {
        type: 'select',
        title: '所属项目',
        key: 'projectId',
        selectOptions: projectOptions,
        rules: [{ required: true, message: comboSelectHolder('所属项目') }],
      },
      {
        type: 'select',
        title: '系统终端',
        key: 'typeSources',
        selectOptions: findDicByCode(dicData, 'commentTypeSources'),
        keyValue: ['dictKey', 'dictValue'],
        rules: [{ required: true, message: comboSelectHolder('系统终端') }],
      },
      {
        type: 'input',
        title: '类型名称',
        key: 'typeName',
        rules: [{ required: true, message: comboHolder('类型名称'), whitespace: true }, { message: '名称长度为2-10位字符', max: 10, min: 2 }],
        maxLength: 10,
      },
      {
        type: 'radio',
        title: '状态',
        key: 'status',
        initialValue: '0',
        options: [
          { label: '启用', value: '1' },
          { label: '禁用', value: '0' },
        ],
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    };
    const searchItems = [
      {
        type: 'select',
        title: '所属项目',
        key: 'projectId',
        selectOptions: projectOptions,
        keyValue: ['value', 'label']
      }
    ];
    const isAdd = filterAuth('userComment_doAddType', permissions, pathname);
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => this.searchForm = val}
            searchItems={searchItems}
            fetchParams={{ type: 'userComment/getFetchPage', url: '/userfeedback/commenttypefindbypage' }}
            saveFormValues={(val: any) => this.setState({ formValues: Object.assign(formValues, val) })}
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {isAdd ? (
            <div className="my_newItem">
              {isAdd ? (
                <Button
                  size="small"
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => this.handleAdd()}
                >
                  新增
                </Button>
              ) : null}
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'userComment/getFetchPage', url: '/userfeedback/commenttypefindbypage' }}
            formValues={formValues}
          />
        </Card>
        <PateoModalForm
          style={{ top: '10%' }}
          formItems={formItems}
          changeVisible={() => this.setState({ formData: {}, visible: false, postUrl: '' })}
          formData={formData}
          visible={visible}
          postUrl={postUrl}
          handleCallback={this.handleFlushPage}
          title={['新增类型', '编辑类型']}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(CommentType);